﻿using FastMvc.Auth;
using FastMvc.Repositories;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;

namespace FastMvc
{
    /// <summary>
    /// 所有Service的基类
    /// </summary>
    public class JQService : IJQService
    {
        #region 登录用户信息
        public UserAuthInfo UserAuth { get; set; }

        public string UserId => UserAuth?.sUserId;

        public string UserName => UserAuth?.sUserName;

        public string OrgId => UserAuth?.sOrgId;

        public string OrgName => UserAuth?.sOrgName;

        public IEnumerable<string> Permissions => UserAuth == null ? new List<string>() : UserAuth.Permissions;


        public void SetUserAuth(UserAuthInfo userAuth)
        {
            this.UserAuth = userAuth;

            // 检查所有的Repository, 下发权限信息
            // 字段
            var fileds = this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
            foreach (var f in fileds)
            {
                if(f.FieldType.FullName.StartsWith("FastMvc.Repositories.IRepository"))
                {
                    var pValue = f.GetValue(this);
                    var authP = f.FieldType.GetProperty("UserAuth");
                    authP.SetValue(pValue, userAuth);
                }
            }
            // 属性
            var ps = this.GetType().GetProperties(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public);
            foreach (var f in ps)
            {
                if (f.PropertyType.FullName.StartsWith("FastMvc.Repositories.IRepository"))
                {
                    var pValue = f.GetValue(this);
                    var authP = f.PropertyType.GetProperty("UserAuth");
                    authP.SetValue(pValue, userAuth);
                }
            }
        }

        #endregion
        protected SqlSugarClient SugarClient
        {
            get
            {
                SqlSugarClient db = null;

                // 设置一下基础的Filter，设置一下数据库路径
                if (this.UserAuth != null)
                {
                    if (this.UserAuth.Claims != null &&
                        this.UserAuth.Claims.ContainsKey("DBConnection"))
                    {
                        var conn = this.UserAuth.Claims["DBConnection"];

                        var sqlConfig = new ConnectionConfig()
                        {
                            ConnectionString = conn,
                            DbType = DbType.MySql,
                            IsAutoCloseConnection = true
                        };
                        if (this.UserAuth.Claims.ContainsKey("DBSlaveConnection"))
                        {
                            sqlConfig.SlaveConnectionConfigs = new List<SlaveConnectionConfig>();
                            var sls = this.UserAuth.Claims["DBSlaveConnection"].Split('|');
                            foreach (var sl in sls)
                            {
                                sqlConfig.SlaveConnectionConfigs.Add(new SlaveConnectionConfig()
                                {
                                    ConnectionString = sl
                                });
                            }
                        }
                        db = new SqlSugarClient(sqlConfig);
                    }
                }
                if (db == null)
                    return DBHelper.SqlSugarDB;

                return db;
            }
        }

        #region 数据转换

        protected TDestination MapTo<TDestination, TSource>(TSource source)
        {
            if (source == null) return default(TDestination);
            var config = new AutoMapper.MapperConfiguration(cfg => cfg.CreateMap<TSource, TDestination>());
            var mapper = config.CreateMapper();
            return mapper.Map<TDestination>(source);
        }
        #endregion
    }
}
